import { Component, OnInit, HostListener, ViewContainerRef, AfterViewInit, Renderer2 } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { filter, switchMap } from 'rxjs/operators';
import { Store } from '@ngrx/store';

import { State } from '../../../store';
import * as fromlayersSelector from '../../store/selectors/layer.selector';
import { FeaturePropertySubjectService } from '../feature-property/feature-property-ref.class';
import { Property } from './properties.model';
import { Layer } from '../../class';

@Component({
  selector: 'ege-properties',
  templateUrl: './properties.component.html',
  styleUrls: ['./properties.component.scss']
})
export class PropertiesComponent implements OnInit {

  data$: Observable<Property[]>;

  constructor(
    private store: Store<State>,
    private options: FeaturePropertySubjectService
  ) { }

  ngOnInit() {
    const layerId: string = this.options.params.layerId;
    const properties: { [key: string]: any } = this.options.params.properties;
    this.data$ = this.serializeProperties(layerId, properties);
  }

  private serializeProperties(layerId: string, properties: { [key: string]: any }): Observable<Property[]> {
    return this.store.select(fromlayersSelector.getAll).pipe(
      switchMap((layers: Layer[]) => {
        const layer: Layer = layers.find(layer => layer.id === layerId);
        let tableColumn: string[];
        let alias: { [key: string]: string } = {};
        let result: Property[] = [];
        if(layer) {
          tableColumn = layer.tableColumn;
          alias = layer.alias || {};
        }
        if(!tableColumn) {
          result = Object.keys(properties).reduce((data, key) => {
            data.push({
              title: alias[key] || key,
              value: properties[key]
            });
            return data;
          }, result);
        } else {
          result = tableColumn.map(column => {
            return {
              title: alias[column] || column,
              value: properties[column]
            };
          });
        }
        return of(result);
      })
    );
  }
  
}
